package com.market.domain.strategy.service.rule.tree.impl;

import com.market.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.market.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.market.domain.strategy.repository.IStrategyRepository;
import com.market.domain.strategy.service.armory.IStrategyDispatch;
import com.market.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.market.domain.strategy.service.rule.tree.factor.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 库存节点
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {

        log.info("规则过滤—库存扣减 userId:{}, strategyId:{}, awardId:{}", userId, strategyId, awardId);
        //开始扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);
        //成功:true、失败:false
        if(status){
            //发异步队列消息,写入延迟队列，延迟队列消费更新数据库记录，【在trigger的job：updateAwardStockJob下消费队列，更新数据库记录】
            repository.awardStockConsumeQueue(StrategyAwardStockKeyVO.builder()
                            .awardId(awardId)
                            .strategyId(strategyId)
                            .build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue("")
                            .build())
                    .build();
        }

        log.warn("规则过滤—库存扣减失败_库存不足 userId:{}, strategyId:{}, awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
